let d1RowsLock = 0;
$NG.AllReady(function (page, { useValuesChange, useImpPullData, useClick, useBeforeClick, useUpdateRow, useUpdateRows, useDataIndexChange }) {
    var mstform = $NG.getCmpApi("p_form_invoice_apply_m");
    var dgrid = $NG.getCmpApi("p_form_invoice_apply_d");

    const toolbar = $NG.getCmpApi("toolbar");
    const toolbar_top = $NG.getCmpApi("toolbar_top");
    const toolbar_dgrid1 = $NG.getCmpApi("toolbar_" + "p_form_invoice_apply_d");
    const toolbar_dgrid2 = $NG.getCmpApi("toolbar_" + "p_form_invoice_apply_d1");
    const toolbars = [
        { toolbar: toolbar_top, items: ["imp"] },
        { toolbar: toolbar_dgrid2, items: ["imp"] },
    ];
    toolbars.forEach(({ toolbar, items }) => {
        if (toolbar && typeof toolbar.getItem === "function") {
            items.forEach((item) => {
                const button = toolbar.getItem(item);
                if (button) {
                    button.setHidden(); // 隐藏按钮
                }
            });
        }
    });


    if (page.oType != 'view' && [1, 0].includes((Number(mstform.getValues().wf_flag) || 0))) {
        getXsCntskInfo()
        if (!mstform.getItem("u_hbkp").getValue()) {
            mstform.getItem("u_hbkp").setValue('0')
        }
    }

    // 根据合同类型隐藏字段
    formatKey()
    function formatKey() {
        const keys = ['u_gfsh', 'u_gfdz', 'u_gfdh', 'u_gfyh', 'u_gfyhzh']
        keys.forEach(item => {
            $NG.updateUI((updater) => {
                updater.fieldSetForm.p_form_invoice_apply_m[item].setProps({
                    required: ![8570000000000792, 8570000000000794].includes(Number(mstform.getItem("u_invoice_type").getValue()) || 0)
                })
            })
        })
        // 判断合同类型

        const all = ["u_gfsh", "u_gfdz", "u_gfdh", "u_gfhh", "u_gfyh", "u_gfyhzh", "u_gfyh_crm"]
        all.forEach(item => {
            $NG.updateUI((updater) => {
                updater.fieldSetForm.p_form_invoice_apply_m[item].setProps({
                    hidden: false,
                    required: false
                })
            })
        })

        switch ((Number(mstform.getItem("u_xshtlx").getValue()) || 0)) {
            case 8570000000000004: // 维修类
                const keys = ['u_gfyh_crm']
                const req1 = ["u_gfsh", "u_gfdz", "u_gfdh", "u_gfyh", "u_gfyhzh", "u_gfyh_crm"]
                keys.forEach(item => {
                    $NG.updateUI((updater) => {
                        updater.fieldSetForm.p_form_invoice_apply_m[item].setProps({
                            hidden: true,
                            required: (item != 'u_gfyh_crm')
                        })
                    })
                })
                req1.forEach(item => {
                    $NG.updateUI((updater) => {
                        updater.fieldSetForm.p_form_invoice_apply_m[item].setProps({
                            required: [8570000000000790, 8570000000000793].includes(Number(mstform.getItem("u_invoice_type").getValue()) || 0)
                        })
                    })
                })

                break
            case 8570000000000001: // 实施服务
            case 8570000000000002: // 订单类
            case 8570000000000003: // 运维类
            case 8570000000000020: // 内部承包

                const keys2 = ['u_gfyh', 'u_gfhh']
                const req2 = ["u_gfsh", "u_gfdz", "u_gfdh", "u_gfyhzh", "u_gfyh_crm"]
                keys2.forEach(item => {
                    $NG.updateUI((updater) => {
                        updater.fieldSetForm.p_form_invoice_apply_m[item].setProps({
                            hidden: true,
                        })
                    })
                })
                req2.forEach(item => {
                    $NG.updateUI((updater) => {
                        updater.fieldSetForm.p_form_invoice_apply_m[item].setProps({
                            required: [8570000000000790, 8570000000000793].includes(Number(mstform.getItem("u_invoice_type").getValue()) || 0)
                        })
                    })
                })
                if (page.oType != 'view') {
                    $NG.updateState((updater) => {
                        updater.data.p_form_invoice_apply_m.setProps({
                            u_gfyhzh: window._catch_cntInfo.user_customer_account,
                            u_gfyh_crm: window._catch_cntInfo.user_customer_yh,
                            u_gfdh: window._catch_cntInfo.user_customer_phone,
                            u_gfdz: window._catch_cntInfo.user_customer_address
                        })
                    })
                }
                break
        }
    }

    useImpPullData(({ args }) => {
        // console.log(`impData`, args[0]);
        // args[0].defaultData.forEach(el => {
        //     sumAmt(el,null,null,true)
        // })
    }, "p_form_invoice_apply_d")
    useValuesChange(({ args }) => {
        formatKey()
    }, "p_form_invoice_apply_m.u_invoice_type")
    useValuesChange(({ args }) => {
        formatKey()
    }, "p_form_invoice_apply_m.u_xshtlx")
    // useDataIndexChange(({ args, instance }) => {
    //     sumAmt(args[0], instance)
    //     instance.updateRow(args[0])
    // }, "p_form_invoice_apply_d.qty")
    useBeforeClick(async () => {
        const rows = dgrid.getRows()
        let lock1 = true
        let lock2 = true
        let isGcfw = []
        // 判断工程服务
        rows.forEach(item => {
            if (item.u_ssfl_no == 4100) {
                isGcfw.push(item)
            }
        })
        if (isGcfw.length != 0) {
            if (isGcfw.length != rows.length) {
                $NG.alert("明细税收分类编码包含工程服务，其他行必须全是工程服务请修改！")
                return false
            }
        }
        for (let i = 0; i < rows.length; i++) {
            const item = rows[i]
            if (item.taxrate != mstform.getItem("u_kpsl").getValue()) {
                lock1 = false
                break
            }
        }

        // 商品名称
        let gc = true
        rows.forEach(el => {
            if (el.u_ssfl_no == 4100) {
                gc = false
            }
        })
        if (!gc) {
            const shapName = rows.reduce((value, item) => {
                value.push(item.u_product_name)
                return value
            }, [])
            if (new Set(shapName).size > 1) {
                lock2 = false
                $NG.alert("工程建筑类的商品名称需一致，请进行修改!")
                return lock2
            }

        }
        let str = ""
        if (!lock1) {
            str += '开票税率与合同评审税率不一致，请修改！'
            return await $NG.confirm(str)
        } else {
            return true
        }
    }, "save")
    toolbar_dgrid1.getItem("imp").setProps({ children: "引用合同清单明细" });
    function hiddenKey() {
        if (page.oType != 'view') {
            ["u_lzfpdm", "u_lzfphm", "u_hzxx"].forEach((field) => {
                $NG.updateUI((updater) => {
                    // sumAmt()
                    // console.log(`updater`, updater);// 删除就报错玄学
                    updater.fieldSetForm.p_form_invoice_apply_m['发票信息'][field].setProps({
                        disabled: page.oType == 'view' || mstform.getItem("u_hllx").getValue() === "1",
                        required: ["u_lzfpdm", "u_hzxx"].includes(field) ? false : !(mstform.getItem("u_hllx").getValue() === "1"),
                    });
                });
            });
            $NG.updateUI((updater) => {
                updater.fieldSetForm.p_form_invoice_apply_m.u_invoice_type.setProps({
                    disabled: mstform.getItem("u_hllx").getValue() == '2',
                });
            });
            // 红票只读数量
            $NG.updateUI((updater) => {
                updater.editGrid.p_form_invoice_apply_d.qty.setProps({
                    disabled: mstform.getItem("u_hllx").getValue() == '2',
                });
            });
            $NG.updateUI((updater) => {
                updater.editGrid.p_form_invoice_apply_d.taxrate.setProps({
                    disabled: mstform.getItem("u_hllx").getValue() == '2',
                });
            });
        }
        const fields = ["u_tdyw", "u_tdzzs_no", "u_jzfwfsd", "u_detail_addr", "u_kdbz", "u_bybh"];
        const pcKeys = ["u_tdzzs_no", "u_detail_addr"]
        let lock = true
        dgrid.getRows().forEach((item) => {
            if(item.u_ssfl_no == 4100){
                lock = false
            }
        });
        if (!lock) {
            if (mstform.getItem("u_hllx").getValue() == '1') {
                $NG.updateUI((updater) => {
                    fields.forEach((field) => {
                        updater.fieldSetForm.p_form_invoice_apply_m[field].setProps({
                            required: true && !pcKeys.includes(field),
                            hidden: false,
                        });
                    });
                });
            }
            if (page.oType != 'view') {
                $NG.updateUI((updater) => {
                    updater.fieldSetForm.p_form_invoice_apply_m.u_hbkp.setProps({
                        disabled: true,
                    });
                });
            }
            $NG.updateState((updater) => {
                updater.data.p_form_invoice_apply_m.setProps({
                    u_hbkp: '1'
                })
            })
        } else {
            $NG.updateUI((updater) => {
                fields.forEach((field) => {
                    updater.fieldSetForm.p_form_invoice_apply_m[field].setProps({
                        required: false,
                        hidden: true,
                    });
                });
            });
            mstform.getItem("u_kdbz").setValue(null)
            // 上面是异步导致下方执行取数有问题
            lock = false
        }
        if (lock && mstform.getItem("u_kdbz").getValue() == '1') {
            $NG.updateUI((updater) => {
                fields.forEach((field) => {
                    updater.fieldSetForm.p_form_invoice_apply_m.u_bybh.setProps({
                        required: true,
                        hidden: false,
                    });
                });
            });
        } else {
            $NG.updateUI((updater) => {
                fields.forEach((field) => {
                    updater.fieldSetForm.p_form_invoice_apply_m.u_bybh.setProps({
                        required: false,
                        hidden: true,
                    });
                });
            });
        }
    }
    // 过滤蓝字号码
    filterMfp()
    function filterMfp() {
        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_invoice_apply_m.u_lzfphm.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!$NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        'cnt.phid': $NG.getCmpApi("p_form_invoice_apply_m").getItem("u_cnt").getValue(),
                        'pt.phid': $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue(),
                        'm.u_sfch': 0,
                    },
                }),
            });
        });
    }

    if (mstform) {
        setTimeout(() => {
            getSumInvInfo(mstform)
            isGcService()
            //init///////////////////////////////
            hiddenKey()
        }, 1000)
        page.oType == 'add' && mstformUpdateUI(mstform);
        // getEnterpriseInfoByPhid(mstform);
        getProjectInfo(mstform);
        cntMFilter();
        if (page.oType == "add") {
            getCntCount();
        }
    }
    if (dgrid) {
        // dgrid1UpdateUI();
        cntDFilter();
    }

    //页面条件
    if (page.oType == "add") {
        kpFilter()
        $NG.execServer("getEpmInfoByUserID", { phid: $NG.getUser().userID }, (res) => {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(datas);
            //   开票申请里的发票类型改为手填20241225
            //   console.log("拿去合同号带出来的发票类型", mstform.getItem("u_invoice_type"));
            //更新UI表格
            $NG.updateState((updater) => {
                //【注意这里的表名不能为控件ID，必须要是表名】
                updater.data.p_form_invoice_apply_m.setProps({

                    u_dept_apply: {
                        value: datas.dept_phid,
                        label: datas.dept_name,
                    },
                });
            });
        });



        const user = $NG.getUser()
        $NG.updateState((updater) => {
            //【注意这里的表名不能为控件ID，必须要是表名】
            updater.data.p_form_invoice_apply_m.setProps({
                u_hr_apply: {
                    value: user.userID,
                    label: user.userName,
                },
                u_dept_apply: {
                    value: user.userID,
                    label: user.userName,
                },
            });
        });
        calculationPay();
    }
    function init() {
        $NG.updateState((updater) => {
            updater.data.p_form_invoice_apply_m.setProps({
                u_invoice_dt: formatDate(new Date(), "yyyy-mm-dd"),
            });
        });
    }
    useValuesChange(({ args }) => {
        console.log(`监听成功`,);
        hiddenKey()
    }, "p_form_invoice_apply_m.u_kdbz")

    useValuesChange(({ args }) => {
        console.log(`蓝字发票监听`, args);
        getLzfpInfo()
        $NG.updateState((updater) => {
            updater.data.p_form_invoice_apply_m.setProps({
                u_lzfpdm: args[0].u_lzfphm.origin.u_fpdm
            })
        })
    }, "p_form_invoice_apply_m.u_lzfphm")

    // 监听字段项目
    useValuesChange(({ args }) => {
        console.log(`监听项目字段`, args);
        cntMFilter();
        getCntCount();
        getProjectInfo(mstform);
        getLcbHkInfo()
        getSumInvInfo(mstform)
        filterMfp()
        $NG.updateState((updater) => {
            updater.data.p_form_invoice_apply_m.setProps({
                u_cnt: {
                    label: null,
                    value: null,
                },
                u_cnt_no: null,
                u_cnt_amt: null,
            });
        });
        kpFilter()
        dgrid.clearRows()
    }, "p_form_invoice_apply_m.phid_pc");

    //表头字段变化逻辑BEGIN
    useValuesChange(({ args }) => {
        getCntMInfoByPhid();
        getXsCntskInfo()
        getProjectInAmtInfo()
        getKpinfoTotalAmt()
        cntDFilter();
        filterMfp()
        kpFilter()
    }, "p_form_invoice_apply_m.u_cnt");

    //监听汇款差额
    useValuesChange(({ args }) => {
        const _data = args[0].u_hkkpce;

        //表头多字段设置属性
        $NG.updateUI((updater) => {
            if (Number(_data) < 0) {
                updater.form.p_form_invoice_apply_m.u_hkcesm.setProps({
                    required: true, //必输
                });
            } else {
                updater.form.p_form_invoice_apply_m.u_hkcesm.setProps({
                    required: false, //必输
                });
            }
        });
    }, "p_form_invoice_apply_m.u_hkkpce");

    useValuesChange(({ args }) => {
        const _data = args[0].u_srkpce;
        //表头多字段设置属性
        $NG.updateUI((updater) => {
            if (Number(_data) < 0) {
                updater.form.p_form_invoice_apply_m.u_srcesm.setProps({
                    required: true, //必输
                });
            }
        });
    }, "p_form_invoice_apply_m.u_srkpce");

    useValuesChange(({ args }) => {
        console.log(`监听银行`, args);
        GetBankInfoByPhid(mstform.getItem("u_gfyh").getValue(), "gf");
        if ((Number(mstform.getItem("u_xshtlx").getValue()) || 0) == 8570000000000004) {
            mstform.getItem("u_gfyh_crm").setValue(mstform.getItem("u_gfyh").getText())
        }
    }, "p_form_invoice_apply_m.u_gfyh");

    useValuesChange(({ args }) => {
        console.log("监听红蓝类型", args);
        isCRed()
        hiddenKey()
    }, "p_form_invoice_apply_m.u_hllx");
    isCRed()
    function isCRed() {
        if (!mstform.getItem("u_hllx").getValue()) return
        const isRed = mstform.getItem("u_hllx").getValue() === "1"; // 蓝字为 true
        sumAmt()
        $NG.updateUI((updater) => {
            updater.fieldSetForm.p_form_invoice_apply_m.u_sfch.setProps({
                hidden: !isRed
            })
        })
        isRed ? mstform.getItem("u_sfch").setValue('0') : mstform.getItem("u_sfch").setValue(null)

        $NG.updateUI((updater) => {
            updater.toolbar.editbar.p_form_invoice_apply_d.imp.setProps({
                disabled: !isRed
            })
        });
    }
    if (page.oType == "add" || page.oType == "edit") {
        let _xfyh = null;
        const _xfTime = setInterval(() => {
            try {
                if (mstform.getItem("u_xfyh").getValue() !== _xfyh) {
                    _xfyh = mstform.getItem("u_xfyh").getValue();
                    GetBankInfoByPhid(mstform.getItem("u_xfyh").getValue(), "xf");
                }
            } catch (err) {
                clearInterval(_xfTime);
                console.log("自定义监听器报错，行号：102");
            }
        }, 1000);

        let _gfyh = null;
        const _gfTime = setInterval(() => {
            try {
                if (mstform.getItem("u_gfyh").getValue() !== _gfyh) {
                    _gfyh = mstform.getItem("u_gfyh").getValue();
                    GetBankInfoByPhid(mstform.getItem("u_gfyh").getValue(), "gf");
                }
            } catch (err) {
                clearInterval(_gfTime);
                console.log("自定义监听器报错，行号：115");
            }
        }, 1000);
    }

    //p_form_invoice_apply_d
    //   let r = null
    //   setInterval(()=>{
    //         if(!r) return
    //         const data = dgrid.getRows()
    //         instance.updateRow(data)
    //     },5000)
    ///////////////////////
    useUpdateRows(({ args, instance }) => {
        const _data = args[0];
        if (window._useUpdateRows_1) {
            clearTimeout(window._useUpdateRows_1)
        }
        window._useUpdateRows_1 = setTimeout(() => {
            isGcService()
            hiddenKey()
            if (!mstform.getItem("u_tdyw").getValue()) {
                mstform.getItem("u_tdyw").setValue({
                    value: "E03",
                    label: "建筑服务",
                });
            }
            dgrid.refreshView();
        }, 500)

    }, "p_form_invoice_apply_d");

    //判断是否是工程服务 过滤编码
    function isGcService() {
        return
        const _data = dgrid.getRows()
        if (_data.some((item) => item.u_ssfl_no == 4100)) {
            _data.forEach((el) => {
                if (el.u_ssfl_no != 4100) {
                    el.u_ssfl_no = undefined
                    el.u_ssfl_no_EXName = undefined
                }
            })
            filter = "itm3_tax_classcode.phid = 4100";
        } else {
            filter = "1=1";
        }
        $NG.updateUI((updater) => {
            const ssflField = updater.editGrid.p_form_invoice_apply_d.u_ssfl_no;
            if (ssflField) {
                ssflField.setProps({ clientSqlFilter: filter });
            }
        });
    }
    function kpFilter() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        const cnt = $NG.getCmpApi("p_form_invoice_apply_m").getItem("u_cnt").getValue();
        if (!phid_pc || !cnt) return
        let phids = []
        $NG.updateUI((updater, state) => {
            $NG.execServer("getKpsqLzxh", { phid_pc: phid_pc, cnt: cnt }, (res) => {
                if (res.count == 0) return
                phids = JSON.parse(res.data).reduce((value, item) => {
                    value.push(item.extendObjects.phid)
                    return value
                }, [])
                console.log(`用过的蓝字发票`, phids);
                if (phids.length == 0) return
                updater.fieldSetForm.p_form_invoice_apply_m.u_lzfphm.setProps({
                    onBeforeOpen: async () => {
                        if (!phid_pc) {
                            $NG.alert("请先选择项目");
                            return false;
                        } else {
                            return true;
                        }
                    },
                    ...(!!$NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue() && {
                        clientSqlFilter: `m.phid not in (${phids.join(',')}) and m.phid_pc ='${phid_pc}' and m.u_cnt = '${cnt}'`
                    }),
                });
            })

        });
    }

    useDataIndexChange(async ({ args, instance }) => {
        console.log(`监听 u_cnt_no`);
        await getCntDInfoByPhid(mstform, args[0]);
        instance.updateRow(args[0]);
    }, "p_form_invoice_apply_d.u_cnt_no");

    useDataIndexChange(async ({ args, instance }) => {
        console.log(`监听税收分类编码`);
        // console.log(`args`, args);
        getItm3TaxClasscode(args[0])
    }, "p_form_invoice_apply_d.u_ssfl_no");

    useDataIndexChange(async ({ args, instance }) => {
        isItno(args[0], true)
        getItm3TaxClasscode(args[0])
        instance.updateRow(args[0]); // 更新界面
    }, "p_form_invoice_apply_d.taxrate");

    //   其他字段编辑触发
    const keys = ["u_msunit", "qty", "taxrate", "prc", "u_vat_prc", "amt", "u_ratee", "u_jshj",
        "u_total_inv_amt", "u_total_inv_amt_vat", "u_yhzc", "u_yhzclx", "u_jzjtlx", "u_kp_remark", "u_remark", "u_hthj"]
    
    // 设置计算队列 计算太快系统会卡，分流太慢会漏行，模拟队列解决
    window._sum_queues = []
    keys.forEach(item => {
        useDataIndexChange(({ args, instance }) => {
            const it = window._sum_queues.findIndex(item => item == args[0])
            if(it == -1){
                window._sum_queues.push(args[0])
            } else {
                window._sum_queues[it] = args[0]
            }
            if (window._sumAmt_lock_data) {
                clearTimeout(window._sumAmt_lock_data)
            }
            window._sumAmt_lock_data = setTimeout(() => {
                sumAmt(args[0], null, null,false,false) // 单字段编译
                instance.updateRow(args[0]); // 更新界面
            }, 700)
        }, "p_form_invoice_apply_d." + item);
    })

    function isItno(row, init = false) {

        if (!init) {
            if (row.u_ssfl_no) {
                return
            }
        }
        switch (Number(row.taxrate)) {
            case 0.13:
            case 0.16:
            case 0.17:
                row.u_ssfl_no = 3499
                row.u_ssfl_no_EXName = "1090513010000000000"
                row.u_ssfl_name = null
                break
            case 0.06:
                row.u_ssfl_no = 3964
                row.u_ssfl_no_EXName = "3040201990000000000"
                row.u_ssfl_name = null
                break
            case 0.09:
                row.u_ssfl_no = 4100
                row.u_ssfl_no_EXName = "3050100000000000000"
                row.u_ssfl_name = null
                break
            default:
                row.u_ssfl_no = null
                row.u_ssfl_no_EXName = null
                row.u_ssfl_name = null
        }
    }
    // 税收分类编码
    function getItm3TaxClasscode(row) {
        $NG.execServer("getItm3TaxClasscode", { phid: row.u_ssfl_no }, function (res) {
            // console.log(res);
            if (res.count > 0) {
                const data = JSON.parse(res.data)[0].extendObjects; //单返回值
                // console.log(data);
                row.u_ssfl_name = data.class_name;
                row.u_ssfljc = data.class_spjm;
                row.u_yhzc = data.preferential;
                row.u_yhzclx = data.preferential_type;
                if (row.u_ssfl_no === 4100) {
                    row.u_pc_zs = 23;
                    row.u_pc_zs_EXName = "9%税率的服务、不动产和无形资产";
                }
            } else {

            }
        });
    }

    //根据合同id获取合同信息
    async function getCntMInfoByPhid(params) {
        $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log("获取合同数据", datas);

            //帮助字段赋值
            //   console.log(`开票税率`,datas.invoice_type_name.match(/.*(\d+)%.*/)?Number(datas.invoice_type_name.match(/.*(\d+)%.*/)[1])/100:null);
            $NG.updateState((updater) => {
                console.log("获取合同数据", datas);
                window._catch_cntInfo = datas
                updater.data.p_form_invoice_apply_m.setProps({
                    u_cnt_amt: datas.cnt_sum_vat_fc,
                    u_cnt_no: datas.pcm_no,
                    //购方信息（客户信息）（收票单位信息）
                    u_gfmc: {
                        //单位名称
                        value: datas.tick_id,
                        label: datas.tick_name,
                    },
                    u_xshtlx: {
                        value: datas.pct_id,
                        label: datas.pct_name
                    },
                    u_gfbm: datas.tick_no, //单位编码
                    u_gfsh: datas.tick_unisocialcredit, //社会信用代码
                    u_gfdz: datas.tick_taxaddress, //单位地址
                    u_gfdh: datas.tick_taxtelephone, //联系电话
                    u_gfyh: {
                        //银行名称
                        value: datas.tick_taxbankid,
                        label: datas.tick_taxbankname,
                    },
                    u_gfyh_crm: datas.tick_taxbankname,
                    u_gfyhzh: datas.tick_taxaccountno, //银行账号
                    //销方信息（供应商信息）（开票单位信息）
                    u_xfmc: {
                        //单位名称
                        value: datas.inv_id,
                        label: datas.inv_name,
                    },
                    inv_no: datas.inv_no, //单位编码
                    u_xfsh: datas.inv_unisocialcredit, //社会信用代码
                    u_xfdz: datas.inv_taxaddress, //单位地址
                    u_xfdh: datas.inv_taxtelephone, //联系电话
                    u_xfyh: {
                        //银行名称
                        value: datas.inv_taxbankid,
                        label: datas.inv_taxbankname,
                    },
                    u_xfyhzh: datas.inv_taxaccountno, //银行账号
                    phid_fcur: {
                        value: datas.phid_fcur,
                        label: datas.phid_fcur_name,
                    },
                    exchangerate: datas.exch_rate,
                    u_kpsl: datas.invoice_type_name ? Number(datas.invoice_type_name.match(/.*?(\d+)%.*/)[1]) / 100 : null
                });
            });
            setTimeout(() => {
                formatKey()
            }, 300)
        });
    }
    // 通过项目过滤合同号 初始化
    function cntMFilter() {
        if (!mstform) return;
        console.log(`正在过滤`);
        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_invoice_apply_m.u_cnt.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue();
                    console.log(`项目名：`, phid_pc);
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!$NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        bill_type: 1, //合同类型
                        phid_pc: $NG.getCmpApi("p_form_invoice_apply_m").getItem("phid_pc").getValue(),
                    },
                }),
            });
        });
    }
    // getLzfpInfo
    page.oType == 'add' && getLzfpInfo()
    function getLzfpInfo() {
        const fphm = mstform.getItem("u_lzfphm").getText()
        if (!fphm) return
        $NG.execServer("getLzfpInfo", { fphm }, (res) => {
            if (res.count == 0) return
            const _temp = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_invoice_apply_m.setProps({
                    u_invoice_type: {
                        value: _temp.u_invoice_type,
                        label: _temp.u_invoice_type_exname
                    }
                })
            })
            let _data = JSON.parse(res.data).reduce((value, item) => {
                delete item.u_invoice_type
                delete item.u_invoice_type_exname
                for (let key in item.extendObjects) {
                    if (key.includes("exname")) {
                        let temp = key.replace("exname", "EXName")
                        item.extendObjects[temp] = item.extendObjects[key]
                        delete item.extendObjects[key]
                    }

                }

                item.extendObjects.prc = (0 - (Number(item.extendObjects.prc) || 0))
                value.push(item.extendObjects)
                return value
            }, [])
            _data.forEach(item => {
                if (item.qty > 0) {
                    item.qty = 0 - item.qty
                }
                // if(item.prc > 0){
                //     item.prc = 0 - item.prc
                // }
                // if(item.u_vat_prc > 0){
                //     item.u_vat_prc = 0 - item.u_vat_prc
                // }
                if (item.amt > 0) {
                    item.amt = 0 - item.amt
                }
                if (item.u_ratee > 0) {
                    item.u_ratee = 0 - item.u_ratee
                }
                if (item.u_jshj > 0) {
                    item.u_jshj = 0 - item.u_jshj
                }
            })
            console.log(`插入的数据`, _data);
            dgrid.clearRows().then(() => {
                dgrid.addRows(_data)
            })
        })
    }
    async function getCntCount() {
        if (!mstform) return;
        console.log(`正在获取合同数量`);
        const phid = mstform.getItem("phid_pc").getValue();
        if (!phid) return;
        $NG.execServer("getCntCount", { type: 1, phid_pc: phid }, function (res) {
            console.log(res);
            if (res.count !== 0) {
                const _datas = JSON.parse(res.data);
                if (_datas.length === 1) {
                    const _data = _datas[0].extendObjects;
                    $NG.updateState((updater) => {
                        updater.data.p_form_invoice_apply_m.setProps({
                            u_cnt: {
                                label: _data.bill_name,
                                value: _data.phid,
                            },
                        });
                        setTimeout(() => {
                            cntDFilter();
                            if (page.oType == "add") {
                                getCntMInfoByPhid();
                                getKpinfoTotalAmt()
                                getXsCntskInfo()
                                getProjectInAmtInfo()
                                kpFilter()
                                filterMfp()
                            }
                        }, 200);
                    });
                }
            }
        });
    }
    window._catch_sumAmt = sumAmt
    //计算本次申请含税/未税金额表头
    function sumAmt(row, instance, rows, bool = false,queuesLock = false) {
        if (page.oType == 'view') return
        let _arr = null
        if (rows) {
            _arr = rows
        } else {
            _arr = dgrid.getData();
        }
        let _count = 0;
        let _count_vat = 0;
        // 内置方法
        const fun = async (item) => {
            isItno(item)
            if (!item.u_ssfl_no || !item.u_ssfl_name) {
                getItm3TaxClasscode(item)
            }
            if (!item.u_kp_remark) {
                item.u_kp_remark = '无'
            }
            if (!bool) {
                // 含税单价
                item.u_vat_prc = (Number(item.u_jshj) || 0) ? (Number(item.u_jshj) || 0) / (Number(item.qty) || 0) : 0
                item.prc = (Number(item.u_vat_prc) || 0) / (1 + (Number(item.taxrate) || 0))
                item.amt = (Number(item.prc) || 0) * (Number(item.qty) || 0)
                item.u_ratee = (Number(item.u_jshj) || 0) - (Number(item.amt) || 0)
            }
            // 累计含税
            let current = window._catch_total_kpamt.filter((it) => {
                if (it.u_cnt_no == item.u_cnt_no) {
                    return it
                }
            })
            if (current.length != 0) {
                item.u_total_inv_amt_vat = (Number(item.u_jshj) || 0) + (Number(current[0].amt_vat) || 0)
                item.u_total_inv_amt = (Number(item.amt) || 0) + (Number(current[0].amt) || 0)

            } else {
                item.u_total_inv_amt_vat = item.u_jshj
                item.u_total_inv_amt = item.amt
            }
            if (item.u_total_inv_amt_vat > item.u_hthj) {
                $NG.alert("累计含税开票金额（含本次）不能超过合同清单价税合计！")
                item.qty = 0
                item.u_ratee = 0
                item.amt = 0
                item.u_jshj = item.u_vat_prc * item.qty
            }
        }

        // 汇总值
        function reduceAmt() {
            _arr.forEach(item => {
                _count += Number(item.amt) || 0;
                _count_vat += Number(item.u_jshj) || 0;

                $NG.updateState((updater) => {
                    updater.data.p_form_invoice_apply_m.setProps({
                        u_amt_total_apply_vat: _count_vat,
                        u_amt_total_apply: _count,
                        u_ljkpje: (Number(window._catch_kpsq_totalAmtVat) || 0) + (Number(_count_vat) || 0),
                        u_ljkpjews: (Number(window._catch_kpsq_totalAmt) || 0) + (Number(_count) || 0),
                        u_srkpce: (Number(mstform.getItem("u_yqrsr").getValue()) || 0) - (window._catch_kpsq_totalAmtVat + _count_vat),
                        u_hkkpce: (Number(mstform.getItem("u_ljhkje").getValue()) || 0) - (window._catch_kpsq_totalAmtVat + _count_vat),
                    });
                });
                if (mstform.getItem("u_hllx").getValue() == '2') {
                    $NG.updateState((updater) => {
                        updater.data.p_form_invoice_apply_m.setProps({
                            u_ljhzfp: Math.abs(_count_vat) + window._catch_total_hzkp
                        });
                    });
                }
            })
        }

        if(window._sum_queues && window._sum_queues.length > 0 && queuesLock){ // 检查是否又队列
            let lock = true
            while(lock){
                if(window._sum_queues.length == 0){
                    lock = false
                } else {
                    fun(window._sum_queues.pop())
                }
            }
            return // 启动队列，不执行下面那些了
        }
        // 是否市单行
        if (row) {
            fun(row)

        } else {
            _arr.forEach((item) => {
                fun(item)
            });
        }
        reduceAmt()
        dgrid.refreshView()
    }

    //新增部分合同详细
    //通过数量和单价计算金额
    function calculationPay() {
        const arr = ["p_form_invoice_apply_d.u_qty", "p_form_invoice_apply_d.u_vat_prc", "p_form_invoice_apply_d.v_amt"];
        arr.forEach((item, index) => {
            useDataIndexChange(({ args, instance }) => {
                console.log(`监听----${item}`, args);
                args[0].u_amt = (args[0].u_qty || 0) * args[0].u_vat_prc || 0;
                instance.updateRow(args[0]);
            }, item);
        });
    }
    // 获取银行行号
    //根据银行主键获取银行信息
    function GetBankInfoByPhid(phid, str) {
        const mstform = $NG.getCmpApi("p_form_invoice_apply_m");
        console.log(`检查传入的参数`, phid, str);
        if (!phid || !str) return;
        $NG.execServer("GetBankInfoByPhid", { phid: phid }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            // console.log(datas);
            if (str == "gf") {
                mstform.getItem("u_gfhh").setValue(datas.bankno);
                console.log(`购方行号：`, datas.bankno);
            } else if (str == "xf") {
                mstform.getItem("u_xfhh").setValue(datas.bankno);
            }
        });
    }
    function sumAmountBeforeDate(dataList, targetDateStr) {
        const targetDate = new Date(targetDateStr);

        return dataList.reduce((sum, item) => {
            const itemDate = new Date(item.u_receivable_dt);
            if (itemDate <= targetDate) {
                return sum + Number(item.u_payable_amt);
            }
            return sum;
        }, 0);
    }
    // 获取开票申请的累计金额
    page.oType != 'view' && getKpinfoTotalAmt()
    function getKpinfoTotalAmt() {
        const cnt = mstform.getItem("u_cnt").getValue()
        if (!cnt) return
        $NG.execServer("getKpinfoTotalAmt", { cnt }, (res) => {
            console.log('获取累计值', res);

            if (res.count == 0) {
                if (page.oType == 'add') {
                    $NG.updateState((updater) => {
                        updater.data.p_form_invoice_apply_m.setProps({
                            u_ljkpje: 0
                        })
                    })
                }
                return
            }
            const _data = JSON.parse(res.data)[0].extendObjects
            window._catch_kpsq_totalAmtVat = _data.total_amt_vat
            window._catch_kpsq_totalAmt = _data.total_amt - (Number(_data.total_ljhzfp_amt) || 0)
            window._catch_total_hzkp = (Number(_data.total_ljhzfp_amt) || 0)
            console.log(`累计计算`, _data.total_amt);
            window._catch_kpinfo_amt = { ..._data }
            if (page.oType == 'add') {
                $NG.updateState((updater) => {
                    updater.data.p_form_invoice_apply_m.setProps({
                        u_ljkpje: window._catch_kpsq_totalAmtVat
                    })
                })
            }
            setTimeout(() => {
                sumAmt()
            }, 500)
        })
    }
    //获取 里程碑计划回款明细金额
    getLcbHkInfo()
    async function getLcbHkInfo() {
        const phid_pc = mstform.getItem("phid_pc").getValue();
        if (!phid_pc) { return; }
        await $NG.execServer("getLcbHkInfo", { phid_pc }, (res) => {
            console.log(`里程碑计划`, res);
            if (res.count == 0) return
            const _data = JSON.parse(res.data).reduce((value, item) => {
                value.push({ ...item.extendObjects })
                return value
            }, [])
            $NG.updateState((updater) => {
                updater.data.p_form_invoice_apply_m.setProps({
                    u_yskje: sumAmountBeforeDate(_data)
                })
            })
        })
    }

    // 获取销售合同收款累计金额
    function getXsCntskInfo() {
        if (page.oType != 'view') {
            const cnt = mstform.getItem("u_cnt").getValue()
            if (!cnt) return
            $NG.execServer("getXsCntskInfo", { cnt }, (res) => {
                console.log(`销售收款`, res);

                if (res.count == 0) return
                const _data = JSON.parse(res.data)[0].extendObjects
                $NG.updateState((updater) => {
                    console.log(`调试debug获取回款`, _data.total_amt, mstform.getItem("u_ljkpje").getValue());
                    updater.data.p_form_invoice_apply_m.setProps({
                        u_ljhkje: _data.total_amt,
                    })
                })
                setTimeout(() => {
                    sumAmt()
                }, 200)
            })
        }

    }
    // 获取累计收入报验的收入报验含税金额
    getProjectInAmtInfo()
    function getProjectInAmtInfo() {
        const cnt = mstform.getItem("u_cnt").getValue()
        if (!cnt) return
        $NG.execServer("getProjectInAmtInfo", { cnt }, (res) => {
            console.log(`收入报验`, res);
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_invoice_apply_m.setProps({
                    u_yqrsr: _data.total_amt_vat,
                    u_yqrsrws: _data.total_amt,
                })
            })
            setTimeout(() => {
                sumAmt()
            }, 200)
        })
    }
    // 格式化日期
    function formatDate(dateStr, outputFormat) {
        const date = new Date(dateStr);

        if (isNaN(date)) {
            return "无效的日期字符串";
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");

        let formattedDate;

        switch (outputFormat) {
            case "yyyy-mm-dd":
                formattedDate = `${year}-${month}-${day}`;
                break;
            case "yyyy-mm-dd HH:mm":
                formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
                break;
            case "yyyy-mm":
                formattedDate = `${year}-${month}`;
                break;
            // 可以根据需要继续添加其他格式的处理逻辑
            default:
                formattedDate = "不支持的输出格式";
        }

        return formattedDate;
    }
    //按照项目和税率获取累计开票金额
    async function getSumInvInfo(mstform, record) {
        console.log(`getSumInvInfo`);
        const phid = mstform.getItem("phid")?.getValue() ?? 0;
        const phid_pc = mstform.getItem("phid_pc")?.getValue();
        let data = {};
        if (!phid_pc) return;
        const res = await new Promise((resolve) => $NG.execServer("getSumInvInfo", { phid_pc: phid_pc, phid: phid }, resolve));
        if (res.count == 0) {
            window._catch_total_kpamt = []
            return
        }
        window._catch_total_kpamt = JSON.parse(res.data).reduce((value, item) => {
            const el = item.extendObjects
            value.push(el)
            return value
        }, [])
        console.log(`获取明细累计`, window._catch_total_kpamt);
        setTimeout(() => {
            sumAmt()
        }, 500)
    }
});

// 获取项目
function getProjectInfo(mstform) {
    console.log(`getPtInfoByPhid`);
    const phid = mstform.getItem("phid_pc")?.getValue();
    if (!phid) return;
    try {
        $NG.execServer("getPtInfoByPhid", { phid: phid }, (res) => {
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            const isYesNoText = (value) => (value === "1" ? "是" : "否");
            $NG.updateState((updater) => {
                updater.data.p_form_invoice_apply_m.setProps({
                    u_pc_no: _data.pc_no, //项目编码
                    u_pc_no: _data.pc_no, //项目编码
                    //事业部or组织
                    phid_org: {
                        value: _data.org_phid,
                        label: _data.org_name,
                    },
                    phid_emp: {
                        label: _data.project_manager_name,
                        value: _data.project_manager_phid,
                    },
                    //售前顾问
                    u_sqgw: {
                        value: _data.user_sqgw_phid,
                        label: _data.user_sqgw_name,
                    },
                    //区域中心
                    u_regional_center: {
                        value: _data.regional_center_phid,
                        label: _data.regional_center_name,
                    },
                    //产品线
                    u_product_line: {
                        value: _data.midwife_phid,
                        label: _data.midwife_name,
                    },
                    //部门
                    u_dept: {
                        value: _data.dept_phid,
                        label: _data.dept_name,
                    },
                    //项目类型
                    u_pc_type: {
                        value: _data.type_phid,
                        label: _data.type_name,
                    },
                    u_jzzz: {
                        value: _data.cwhszz,
                        label: _data.cwzz_name,
                    },

                    u_sfqf: { value: _data.user_sf_qf, label: isYesNoText(_data.user_sf_qf) }, // 这里将数值转换为文本描述
                });
            });
        });
    } catch (err) {
        $NG.alert("获取项目信息发生失败请检查~");
    }
}

// 获取企业信息
function getEnterpriseInfoByPhid(mstform) {
    // 禁用
    return
    console.log("getEnterpriseInfoByPhid");
    const phid_org = mstform.getItem("phid_org");
    if (!phid_org) return;

    const phidValue = phid_org.getValue();
    if (!phidValue) return console.warn("phid_org 为空，无法获取企业信息");

    $NG.execServer("getEnterpriseInfoByPhid", { phid: phidValue }, (res) => {
        if (res.count == 0) return;
        try {
            const datas = JSON.parse(res.data)[0].extendObjects;
            if (!datas) return;
            // console.log("组织信息", datas);
            $NG.updateState((updater) => {
                updater.data.p_form_invoice_apply_m.setProps({
                    u_xfmc: datas.compname,
                    u_xfsh: datas.unisocialcredit,
                    u_xfdz: datas.taxaddress,
                    u_xfdh: datas.taxtelephone,
                    u_xfyhzh: datas.bankno,
                    u_xfyh: datas.taxbankname,
                    u_xfhh: datas.taxaccountno,
                });
            });
        } catch (error) {
            console.error("解析企业信息出错", error);
        }
    });
}
// 获取供应商信息（销房）
function searchGys(phid) {
    if (!phid) return
    $NG.execServer("searchGys", { phid }, (res) => {
        if (res.count == 0) return
        const _data = JSON.parse(res.data)[0].extendObjects
        $NG.updaterUI((updater) => {
            updater.data.p_form_invoice_apply_m.setProps({
                u_xfsh: _data.taxaccountno,
                u_xfdz: _data.user_zc_address,
                u_xfdh: _data.taxtelephone,
                u_xfhh: _data.user_yhhh,
                u_xfyh: {
                    label: _data.taxbankname,
                    value: _data.taxbank_id
                },
                u_xfyhzh: _data.user_yhzhmc
            })
        })
    })
}




function mstformUpdateUI(mstform) {
    mstform.getItem("u_hllx").setValue({
        value: "1",
        label: "蓝字发票",
    });
}

function cntDFilter() {
    $NG.updateUI((updater) =>
        updater.editGrid.p_form_invoice_apply_d.u_cnt_no.setProps((p) => {
            return {
                ...p,
                editor: {
                    ...p.editor,
                    clientSqlFilter: {
                        pphid: $NG.getCmpApi("p_form_invoice_apply_m").getItem("u_cnt").getValue() || 0,
                    },
                },
            };
        })
    );
}

async function getCntDInfoByPhid(mstform, record) {

    try {
        const cndId = mstform.getItem("u_cnt")?.getValue();
        const phid = record.u_cnt_no;

        const res = await new Promise((resolve) => $NG.execServer("getCntDInfoByPhid", { cnd_id: cndId, phid }, resolve));

        console.log(res);

        if (res.count > 0 && res.data) {
            const parsed = JSON.parse(res.data);
            const data = parsed[0]?.extendObjects;

            if (data) {
                record.u_cnt_name = data.item_name || ""; // 合同清单编码
                record.u_ggxh = data.user_ggxh || ""; // 规格型号
                record.u_msunit = data.unit_phid || "";
                record.u_msunit_EXName = data.unit_name || ""; // 计量单位
                record.qty = data.qty || 0; // 数量
                record.taxrate = data.taxrate || 0; // 税率
                record.prc = data.prc_fc || 0; // 未税单价
                record.u_vat_prc = data.prc_vat_fc || 0; // 含税单价
                record.amt = data.amt_fc || 0; // 未税金额
                record.u_jshj = data.amt_vat_fc || 0; // 含税金额
                record.u_ratee = record.u_jshj - record.amt; // 税额
            } else {
                console.warn("extendObjects 数据为空");
            }
        } else {
        }
    } catch (error) {
        console.error("getCntDInfoByPhid 异常：", error);
    }
}
